<?php

namespace app\middleware;

use app\libs\exception\ForbiddenException;
use app\libs\tool\CacheTool;
use think\Response;

class Access
{
    /**
     * @throws ForbiddenException
     */
    public function handle($request, \Closure $next): Response
    {
        $url = strtolower($request->baseUrl());
        $method = strtolower($request->method());
        $route = CacheTool::getCache(config('secure.allow_route'));

        $current_request = [
            'method' => $method,
            'url' => $url
        ];

        // 白名单
        $white = config('secure.white_route');
        if (in_array($current_request, $white)) {
            return $next($request);
        }

        if (!in_array($current_request, $route)) {
            throw new ForbiddenException();
        }

        return $next($request);
    }
}